﻿using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Text;
using System.Xml;

namespace WCS.Services
{
    public class MesWmsToolHelper
    {
        private readonly ILogger<MesWmsToolHelper> logger;
        private readonly IHttpClientFactory httpClientFactory;
        public MesWmsToolHelper(ILogger<MesWmsToolHelper> logger, IHttpClientFactory httpClientFactory)
        {
            this.logger = logger;
            this.httpClientFactory = httpClientFactory;
        }

        /// <summary>
        /// 与MES进行二次校验信息
        /// </summary>
        /// <param name="url"></param>
        /// <param name="param"></param>
        /// <returns></returns>
        public async Task<bool> CheckMesInfo(string url, JObject param)
        {
            try
            {
                var httpClient = httpClientFactory.CreateClient();

                string content = $@"<soapenv:Envelope xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" xmlns:soapenv=""http://schemas.xmlsoap.org/soap/envelope/"" xmlns:wsdd=""http://xml.fa-software.com/mycim/wsdd/"">
                                  <soapenv:Header/>
                                  <soapenv:Body>
                                    <wsdd:agvCheckMaterialTwo soapenv:encodingStyle=""http://schemas.xmlsoap.org/soap/encoding/"">
                                     <lineId xsi:type=""soapenc:string"" xmlns:soapenc=""http://schemas.xmlsoap.org/soap/encoding/"">{param.Value<string>("lineId").Trim()}</lineId>
                                       <shiftId xsi:type=""soapenc:string"" xmlns:soapenc=""http://schemas.xmlsoap.org/soap/encoding"">{param.Value<string>("shiftId")}</shiftId>
                                       <itemInfo xsi:type=""soapenc:string"" xmlns:soapenc=""http://schemas.xmlsoap.org/soap/encoding/"">{JsonConvert.SerializeObject(param.Value<JObject>("itemInfo"))} </itemInfo>
                                    </wsdd:agvCheckMaterialTwo>
                                  </soapenv:Body>
                                </soapenv:Envelope>";
                HttpContent httpContent = new StringContent(content, Encoding.UTF8, "application/xml");
                httpContent.Headers.Add("SOAPAction", "");
                logger.LogInformation("Double check send mes info is:{0}", content);
                HttpResponseMessage response = await httpClient.PostAsync(url, httpContent);
                var datas = await response.Content.ReadAsStringAsync();
                logger.LogInformation("Double check receive mes info is:{0}", datas);
                //XML 解析数据
                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.LoadXml(datas);
                XmlNamespaceManager nsmgr = new XmlNamespaceManager(xmlDoc.NameTable);
                XmlElement root = xmlDoc.DocumentElement;
                XmlNode xnode = root.FirstChild;
                nsmgr.AddNamespace("ns1", "http://xml.fa-software.com/mycim/wsdd/");
                var value = xnode.SelectSingleNode("//ns1:agvCheckMaterialTwoResponse", nsmgr).SelectSingleNode("agvCheckMaterialTwoReturn").InnerText;
                logger.LogInformation("Double check receive mes info body  is:{0}", value);
                return JObject.Parse(value).Value<bool>("success");


            }
            catch (Exception ex)
            {
                logger.LogError("Double mes check occurs error ,the error info is:{0}", ex.Message);
                return false;
            }
        }


        /// <summary>
        /// 给WMS报告投料信息
        /// </summary>
        /// <param name="url"></param>
        /// <param name="param"></param>
        /// <returns></returns>
        public async Task<bool> FeedingToWms(string url, JArray param, string username = "WMS", string password = "wms1234")
        {
            try
            {
                var httpClient = httpClientFactory.CreateClient();

                string content = $@"<?xml version=""1.0"" encoding=""UTF-8"" ?>
                             <PROCESS_Input xmlns=""http://xmlns.oracle.com/apps/cux/rest/CuxDwmsAgvInfo/process/"">
                                <RESTHeader xmlns=""http://xmlns.oracle.com/apps/fnd/rest/header"">
                                    <Responsibility></Responsibility>
                                    <RespApplication></RespApplication>
                                    <SecurityGroup></SecurityGroup>
                                    <NLSLanguage>SIMPLIFIED CHINESE</NLSLanguage>
                                    <Org_Id>0</Org_Id>
                                </RESTHeader>
                                <InputParameters>
                                   <P_INPUT_DATA>{JsonConvert.SerializeObject(param)}</P_INPUT_DATA>
                                </InputParameters>
                             </PROCESS_Input>";
                HttpContent httpContent = new StringContent(content, Encoding.UTF8, "application/xml");
                var usernamePassword = $"{username}:{password}";
                httpClient.DefaultRequestHeaders.Add("Authorization", "Basic " + Convert.ToBase64String(Encoding.UTF8.GetBytes(usernamePassword)));
                logger.LogInformation("Feeding wcs send wcs info is:{0}", content);
                HttpResponseMessage response = await httpClient.PostAsync(url, httpContent);
                var datas = await response.Content.ReadAsStringAsync();
                logger.LogInformation("Feeding wcs receive wcs info is:{0}", datas);
                //XML 解析数据
                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.LoadXml(datas);
                string value = xmlDoc.InnerText;
                logger.LogInformation("Feeding wcs receive wcs infobody  is:{0}", value);
                var das = JArray.Parse(value);
                return das[0].Value<string>("PROCESS_STATUS") == "S";


            }
            catch (Exception ex)
            {
                logger.LogError("Feeding wcs  occurs error ,the error info is:{0}", ex.Message);
                return false;
            }
        }

    }
}
